const createError = require('http-errors');
const cors = require('cors')
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const config = require('./common/config');
const {createWebsocketServer} = require('./common/websocketServer');

const bussinessRouter = require('./routes/bussiness/index');

const app = express();
app.use(cors())
createWebsocketServer(app)

app.listen(config.port, () => {
  console.log(`robot-wms-sow服务启动完成，端口监听${config.port}！`)
})

//设置允许跨域访问该服务.--测试用
// app.all('*', (req, res, next) => {
//   res.header('Access-Control-Allow-Origin', '*')
//   res.header(
//       'Access-Control-Allow-Headers',
//       'Content-Type,Content-Length, Authorization, Accept,X-Requested-With'
//   )
//   res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
//   res.header('X-Powered-By', ' 3.2.1')
//   res.header('Content-Type', 'application/json')
//   if (req.method == 'OPTIONS') res.send(200) /*让options请求快速返回*/
//   else next()
// })

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json({limit: '500mb'}));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/public',express.static(__dirname+'/public',{
  maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
}));

//业务模块
Object.keys(bussinessRouter).forEach(key => {
  app.use('/xunfei',bussinessRouter[key]);
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.log(err)

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
